#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# TabPanel.py

import wx
import sys
import os
import shutil
currentFilePath = __file__
parentPath = os.path.dirname(currentFilePath)
oriPath = os.path.dirname(parentPath)
sys.path.append(oriPath)
from listDir import listDir
from listDir import findFile
from copyZip import copyDir
#from Common.listDir import listDir

class TabPanel(wx.Panel):
    '''
    This will be th first notebook tab
    '''
    #----------------------------------------
    def __init__(self,*args):
        wx.Panel.__init__(self,*args)
        print(oriPath)
        orimodel =  listDir(oriPath+"/Template")
        # if len(orimodel.keys())<1:
        #     print("请检查模版文件")
            # dial = wx.MessageDialog(None,'Download completed','info',wx.OK)
            # dial.ShowModal()
        self.__oriModel = orimodel
        self.__oriRes = []
       # self.__oriRes = findFile(oriPath+"/zip",)
        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL) #水平方向添加约束,约束之间可以叠加
        label = wx.StaticText(self, -1, u"选择将要生成的帖纸类型:")
        list1 = self.__oriModel.values()
        if list1==None or len(list1)<1:
            print("当前系统没有检测到模版文件")
        ch1=wx.ComboBox(self,choices=list1,style=wx.CB_READONLY,size=(120,29))
        self.typeCombo = ch1
        hbox1.Add(label,0,wx.LEFT|wx.ALIGN_CENTER_VERTICAL,-20)
        hbox1.Add(ch1,2,wx.LEFT|wx.ALIGN_CENTER_VERTICAL,10)
        vbox.Add(hbox1,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,35)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        label2= wx.StaticText(self, -1, u"选择将要生成的帖纸名字:")
        textBox = wx.TextCtrl(self, 0,size=(120,22))
        self.__stickerNameText = textBox
        hbox2.Add(label2,1,wx.RIGHT|wx.ALIGN_CENTER_VERTICAL,7)
        hbox2.Add(textBox,0,wx.ALIGN_CENTER_VERTICAL|wx.RIGHT,20)
        vbox.Add(hbox2,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,30)
        
        hbox30 = wx.BoxSizer(wx.HORIZONTAL)
        lblList = ['yes', 'no']
        rbox = wx.RadioBox(self,label = '是否使用系统缓存资源文件', choices = lblList ,
   majorDimension = 1, style = wx.RA_SPECIFY_ROWS)
        self.__rbox = rbox
        rbox.SetSelection(1)
        rbox.Bind(wx.EVT_RADIOBOX,self.onRadioBox)
        hbox30.Add(rbox,0)
        vbox.Add(hbox30,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,30)

        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        btn = wx.Button(self,-1,"点击上传资源文件")
        btn.Bind(wx.EVT_BUTTON, lambda evt,mark="":self.OnClicked(evt,""))
        self.__uploadRes = btn
        #btn.Disable()
        hbox3.Add(btn,0)
        vbox.Add(hbox3,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,30)
        #hbox3.AddStretchSpacer() 

        hbox4 = wx.BoxSizer(wx.HORIZONTAL)
        scroller = wx.ScrolledWindow(self, id=-1, pos=wx.DefaultPosition,  #wx.VSCROLL
                                     size=(300,150), style=wx.HSCROLL,
                                     name="scrolledWindow")
        scroller.SetBackgroundColour("Gray")
        scroller.SetScrollbars(1, 1, 1440, 900)
        hbox4.Add(scroller,0)
        vbox.Add(hbox4,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,30)
        
        label3= wx.StaticText(scroller, -1, u"")
        self.__scrollerLabel = label3

        hbox5 = wx.BoxSizer(wx.HORIZONTAL)
        btn2 = wx.Button(self,-1,"      \n生成贴纸\n     ",size=(100,60))
        btn2.Bind(wx.EVT_BUTTON, lambda evt,mark="":self.OnClicked2(evt,""))
        hbox5.Add(btn2,0)
        vbox.Add(hbox5,0,wx.ALIGN_CENTER_HORIZONTAL|wx.TOP,30)
        self.SetSizer(vbox)

       
    def onRadioBox(self,e):
        if self.__rbox.GetStringSelection()=="yes":
            self.__oriRes = findFile(oriPath+"/zip",self.__stickerNameText.GetValue())
            name = ""
            if len(self.__oriRes)>0:
                for i in self.__oriRes:
                    if len(name)>0:
                        name = name+"\n"+i
                    else:
                        name = name + i
            else:
                name = u"贴纸名字为空，或者当前系统没有缓存该名字的资源文件！\n请核查贴纸名字！"
            self.__scrollerLabel.SetLabel(name)
            self.__uploadRes.Disable()
        else:
            self.__scrollerLabel.SetLabel("")
            self.__uploadRes.Enable()
    def OnClicked(self, event,parm): 
        # btn = event.GetEventObject().GetLabel() 
        # print("Label of pressed button = ", self.__comboBox.GetValue())
        self.__MultipleSelectFiles()
    def OnClicked2(self, event,parm):
        name = self.__stickerNameText.GetValue() #贴纸名字
        if len(name)<1 or len(self.__oriRes)<1:
            Pdial2 = wx.MessageDialog(self,"请检查是否填写贴纸名字，或者是否上传资源文件",'小提示',wx.OK)
            Pdial2.ShowModal()
            return
        #判断有没有同名字的贴纸
        productName = oriPath+"/Product/"
        if os.path.exists(productName+name):
            Pdial = wx.MessageDialog(self,'已经生成过名字为：'+name+"的贴纸，是否要重新生成？",'小提示',wx.YES_NO | wx.ICON_QUESTION)
            if Pdial.ShowModal() == wx.ID_NO:
                return
            else:
                shutil.rmtree(productName)
                pass
        currentPaths = []
        if self.__rbox.GetStringSelection()=="yes":
            if len(self.__oriRes)>0:
                currentPaths = self.__oriRes
            else:
                pass
                #没有资源文件
        else:
            if os.path.exists(oriPath+"/zip"+"/"+name+"/"):
                shutil.rmtree(oriPath+"/zip"+"/"+name+"/")
            for i in range(len(self.__oriRes)):
                copyDir(name,self.__oriRes[i],oriPath+"/zip"+"/"+name+"/")
                fileName = os.path.basename(self.__oriRes[i])
                newFile = oriPath+"/zip"+"/"+name+"/" +fileName
                currentPaths.append(newFile)
        #print(currentPaths)
        # print(self.typeCombo.GetValue())
        # print(self.__oriModel)
        TemplateName = self.get_key(self.__oriModel, self.typeCombo.GetValue())[0]
        print(TemplateName)
        print(self.get_key(self.__oriModel,self.typeCombo.GetValue()))
        modulePath="Template."+str(TemplateName)+"."+str(TemplateName)
        print(modulePath)
        try:
            module=__import__(modulePath)
        except ModuleNotFoundError:
            print("没有该模块")
            exit(0)
        else:
            productName=name
            module=__import__(modulePath)
    
            firstModule=getattr(module, TemplateName)

            secondModule=getattr(firstModule, TemplateName)
   
            templateName=getattr(secondModule, TemplateName)
           
            if hasattr(templateName, '__init__'):
                #  print(templateName)
                print(currentPaths)
                template=templateName(currentPaths)
                template.CreateIndexAndMetadataJson()
                template.CopySpecificResource()
                # 创建node拷贝资源    
                template.createAndCopyNodesResource(currentPaths,productName)
                print(template.getOutPutPath)
            else:
                 print("没有该类")
                 exit(0)
        # for zippath in self.__oriRes:
        #     copyDir(name,zippath,oriPath+"/zip"+"/"+name+"/")
        
        # dial = wx.MessageDialog(self,'贴纸路径为：','成功生成贴纸',wx.OK)
        # dial.ShowModal()    
    def get_key (self,dict, value):
        return [k for k, v in dict.items() if v == value]
    def __MultipleSelectFiles(self):
        #"Dicom (*.dcm)|*.dcm|" "All files (*.*)|*.*"
        filesFilter = "*.zip"
        fileDialog = wx.FileDialog(self, message ="多文件选择", wildcard = filesFilter, style = wx.FD_OPEN|wx.FD_MULTIPLE)
        dialogResult = fileDialog.ShowModal()
        if dialogResult !=  wx.ID_OK:
            return
        paths = fileDialog.GetPaths()
        self.__scrollerLabel.SetLabel('')
        self.__oriRes = []
        for path in paths:
            self.__oriRes.append(path)
            oriPath = self.__scrollerLabel.GetLabel()
            if len(oriPath)>0:
                oriPath = oriPath+"\n"+path
            else:
                oriPath = oriPath+path
            self.__scrollerLabel.SetLabel(oriPath)
    def checkRes(self):
        if len(self.__oriRes)<1:
            print("请检查模版文件")
            dial = wx.MessageDialog(self,'Download completed','info',wx.OK)
            dial.ShowModal()
        #self.__oriModel = orimodel
        print("检查资源")